import * as React  from 'react';

import './DemoGetSnapshotBeforeUpdate.css';

class DemoGetSnapshotBeforeUpdate extends React.Component<{}, { newsArr: string[] }, any> {
    private list: any;

    constructor(props: any) {
        super(props);
        this.state = { newsArr: [] };
    }

    componentDidMount() {
        setInterval(() => {
            const { newsArr } = this.state;
            const news = 'news ' + (newsArr.length + 1);
            this.setState({
                newsArr: [news, ...newsArr]
            });
        }, 1000);
    }

    getSnapshotBeforeUpdate() {
        return this.list.current.scrollHeight;
    }

    componentDidUpdate(preProps: any, preState: any, height: number) {
        debugger;
        this.list.current.scrollTop += this.list.current.scrollHeight - height;
    }

    render() {
        return (
            <div className='list' ref={list => {
                this.list = list;
              }}>
                {
                    this.state.newsArr.map((n, index) => {
                        return <div className='news' key={index}>{n}</div>
                    })
                }
            </div>
        )
    }
}

export default DemoGetSnapshotBeforeUpdate;
